package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.LoginException;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.UserContext;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.IPUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private IEmployeeService employeeService;

    @RequestMapping("/userLogin")
    @ResponseBody
    public JsonResult login(String username, String password, HttpSession session, HttpServletRequest request) {
        JsonResult jsonResult = new JsonResult();
        Employee employee = employeeService.selectUserExists(username, password, request);

        if (!employee.isStatus()) {
            throw new LoginException("账号被禁用");
        }
        UserContext.setEmployee(employee);
        //session.setAttribute("USER_IN_SESSION", employee);

        //通过用户id去查询用户拥有所有权限的集合
        List<String> permissions = employeeService.selectEmployeePermission(employee.getId());
        UserContext.setPermissions(permissions);


        jsonResult.setSuccess(true);
        jsonResult.setMsg("登陆成功");

        return jsonResult;
    }

    @RequestMapping("/userLogout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login.html";
    }

    /*没权限跳转页面*/
    @RequestMapping("/nop")
    public String nop() {
        return "common/nopermission";
    }

}
